<template>
    <div class="login-wrapper">
        <div class="modal">
            <h2 class="title">通用后台管理系统</h2>
            <el-form :model="users" ref="userForm" :rules="rules">
                <el-form-item label="用户名:" prop="userName">
                    <el-input placeholder="请输入用户名" prefix-icon="user" v-model="users.userName" />
                </el-form-item>
                <el-form-item label="密&nbsp;&nbsp;&nbsp;码:" prop="userPwd">
                    <el-input type="password" placeholder="请输入密码" prefix-icon="lock" v-model="users.userPwd" />
                </el-form-item>
                <el-form-item>
                    <el-button class="btn-login" type="primary" @click="login">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
    import {
        inject,
        ref
    } from 'vue'

    import {
        useRouter
    } from 'vue-router'

    const users = ref({
        userName: '',
        userPwd: ''
    })

    //定义验证规则 
    //userName属性必填项  文本框失去焦点验证
    const rules = ref({
        userName: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        }],
        userPwd: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }]
    })
    //获得组件中ref属性值为userForm的表单元素
    const userForm = ref()
    const $api = inject("$api")
    const router = useRouter()
    import {
        useStore
    } from 'vuex'

    const store = useStore()

    const login = () => {
        userForm.value.validate((valid) => {
            if (valid) {
                $api.login(users.value).then(res => {
                    //将用户的信息保存本地存储中(使用Vuex)  
                    store.commit('saveUserInfo', res)
                    //如果登录成功跳转到home页面上
                    router.push("/home")
                })
            }
        })
    }
</script>

<style scoped>
    .login-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f9fcff;
        width: 100vw;
        height: 100vh;

        .modal {
            width: 500px;
            padding: 50px;
            background: #fff;
            border-radius: 5px;
            box-shadow: 0px 0px 10px 3px #c7c9c7;

            .title {
                font-size: 25px;
                line-height: 1.5;
                text-align: center;
                margin-bottom: 30px;
            }

            .btn-login {
                width: 100%;
            }
        }
    }
</style>